var express = require("express");
var router = express.Router();
const XLSX = require("xlsx");
const axios = require("axios");
const filePrefix =
  "https://c1api-gateway.kjtpay.com/api-gateway/getFile?fileName=";

router.post("/national_template", async function (req, res, next) {
  const { fileUrl, sheetName } = req.body;
  if (fileUrl) {
    const xlsxContent = await getXlsx(fileUrl, sheetName);
    if (!xlsxContent) {
      res.json({
        code: "S0002",
        message: `提交模版中不存在表${sheetName}`,
      });
    } else {
      res.json({
        code: "S0001",
        bizContent: {
          xlsxContent,
        },
      });
    }
  }
});

async function getResponseByXlsxPath(path) {
  return await axios({
    url: path,
    method: "GET",
    responseType: "arraybuffer", // 设置响应类型为ArrayBuffer
  });
}
async function getXlsx(filePath, sheetName) {
  const completePath = filePrefix + filePath;
  const response = await getResponseByXlsxPath(completePath);
  const workbook = XLSX.read(response.data, { type: "buffer" });
  // 获取工作表的名称列表
  const sheetNames = workbook.SheetNames;
  const targetSheet = sheetNames.find((item) => item === sheetName);
  //   未找到xlsx对应表
  if (!targetSheet) {
    return false;
  }
  // 使用第一个工作表
  const sheet = workbook.Sheets[sheetName];
  // 将工作表对象转换为JSON
  const data = XLSX.utils.sheet_to_json(sheet);
  return data;
}

module.exports = router;
